<?php

// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------

namespace Home\Controller;

use Think\Controller;

class PublicController extends Controller {
    
    public function alert_login(){
        $url = I('url');
        $this->assign('url', $url);
        $this->display();
    }
    
    public function do_login() {
        $username = I('post.username');
        //判断用户输入的是用户名，或手机号，或邮箱
        $password = I('post.password');
        //去除前后空格
        $username = trim($username);
        $userType = userLoginType($username);
        if ($userType == 1) {
            $map['user_email'] = array('eq', $username); //邮箱登陆
        } else if ($userType == 2) {
            $map['user_mobile'] = array('eq', $username); //手机号登陆
        }
        $user = M('users')->where($map)->find(); //查找用户
        
        if (!$user) {
            $a['info'] = "账户不存在，请注册后再试！";
            $a['status'] = FALSE;
            echo json_encode($a);
        }else{
            if ($user['user_state'] == 1) {
                if($password !=0){
                    list($passwords, $salt) = password($password, $user['user_salt']);
                    if ($passwords != $user['user_passwd']) {
                        $a['info'] = "密码不正确！";
                        $a['status'] = FALSE;
                        echo json_encode($a);
                        exit;
                    }
                }
                //更新登录信息
                $data = array(
                    'user_id' => $user['user_id'],
                    'user_login_num' => array('exp', '`user_login_num`+1'),
                    'user_login_time' => time(),
                    'user_login_ip' => get_client_ip(1),
                );
                M('users')->save($data);
                session('user_id', $user['user_id']);
                session('user_name', $user['user_name']);
                $a['info'] = "登陆成功";
                $a['status'] = TRUE;
                echo json_encode($a);
            } else {
                $a['info'] = "账户异常，请联系客服！";
                $a['status'] = FALSE;
                $a['url'] = U('Index/index');
                echo json_encode($a);
            }
        }
    }
    

    //订单自动取消
    //自动取消到期的优惠券
    public function cannelOrder(){
       //获取相对应的所有订单
        $where['order_state'] = 10;
        $where['add_time'] = array('lt',time()-60*60*24);
        $data['order_state'] = 0;
        $re = M('order')->where($where)->save($data);
        //p(M('order')->getLastSql());
        p($re);
        
        //自动过期优惠券
        $where2['voucher_end_date'] = array('lt',NOW_TIME);
        $data2['voucher_state'] = 3;
        $res = M('p_voucher')->where($where2)->save($data2);
        p($res);
        
        //更新秒杀销售的数量
        $Order = M("order_goods");
        $map['seckil_type'] = 1;
        $map['seckill_state'] = 1;
        $seckill = M('seckill')->where($map)->select();
        foreach ($seckill as $key => $value){
            $whe['oi.goods_id'] = $value['seckill_goods_id'];
            $whe['oi.goods_type'] = 4;
            $whe['os.order_state'] = array('EGT', 20);
            $count[$key] = $Order->alias('oi')->join('LEFT JOIN __ORDER__ os ON oi.order_id = os.order_id')->where($whe)->count();
            M('seckill')->where('seckill_id='.$value['seckill_id'])->setField('seckill_sale',$count[$key]);
        }
        
    }

    
    /**
     * 功能：UpYun通过Ajax上传图片
     * @param 
     * @return 返回图片的地址
     */
    public function upload() {
        header("Access-Control-Allow-Origin:*");
        $upyun = new \Libs\UpYun();
        $file = $_FILES['image'];
        $url = $upyun->upload($file);
        $arr['status'] = 1;
        $arr['msg'] = $url;
        $this->ajaxReturn($arr, 'JSON');
    }

    /**
     * 功能：UpYun通过Ajax上传图片
     * @param 
     * @return 返回图片的地址
     */
    public function ueditor() {
        header("Access-Control-Allow-Origin: *");
        $upyun = new \Libs\UpYun();
        $file = $_FILES['upfile'];
        $url = $upyun->upload($file);
        if ($url) {
            $result = ['state' => 'SUCCESS', 'url' => $url, 'title' => $file['name']];
        } else {
            $result = ['state' => '图片上传失败！'];
        }
        echo json_encode($result);
    }

    /**
     * 功能：支付结果返回
     */
    public function notify() {
        /*
         * 支付回调 - 记录支付宝透传参数
         *  step = 3  ,不做任何处理的支付宝透传参数
         */
        $apitype = I('get.apitype');
        $pay = new \Libs\Pay($apitype, C('PAY_' . $apitype));
        if (IS_POST && !empty($_POST)) {
            $notify = $_POST;
        } elseif (IS_GET && !empty($_GET)) {
            $notify = $_GET;
            unset($notify['method']);
            unset($notify['apitype']);
        } else {
            exit('Access Denied');
        }
        //验证
        if ($pay->verifyNotify($notify)){
            //获取订单信息
            $info = $pay->getInfo();
            if ($info['status']) {
                $payinfo = M("orderPay")->where(array('pay_sn' => $info['out_trade_no']))->find();
                //file_put_contents('222.txt', $payinfo);
                if ($payinfo['status'] == 10 && !empty($payinfo['callback'])) {
                    //file_put_contents('666.txt', $payinfo['status'].'|||'.$payinfo['callback'].'|||'.$payinfo['total'].'|||'.$payinfo['pay_sn']);
                    session("pay_verify", true);
                    
                    //$check = R('Pay/tradePay', array('money' => $payinfo['total'], 'trade_id' => $payinfo['pay_sn']));
                    //订单结算
                    $map['pay_sn'] = $payinfo['pay_sn'];        
                    $oModel = D('Order');
                    $oList = $oModel->relation('OrderGoods')->where($map)->select();
                    //获取平台的优惠券的信息
                    $maps['pay_sn'] = $payinfo['pay_sn'];
                    $maps['voucher_store'] = 0;
                    $tddList = M('order_voucher')->where($maps)->select();
                    if (!empty($tddList)) {
                        foreach ($tddList as $key => $value) {
                            $totalTdd += $value['voucher_price'];
                        }
                    }
                    $bili = (1 - $totalTdd/($payinfo['total']+$totalTdd)); //平台优惠比例
                    foreach ($oList as $key => $value) {
                        if ($value['discount_fee'] > 0) {
                            foreach ($value['OrderGoods'] as $k => $v) {
                                $pay_price[$k] = $bili * $v['goods_price'] * $v['goods_num'];
                                $trader_price += $bili * $v['goods_price'] * $v['goods_num'];
                            }
                            $bili2 = (1 - ($value['discount_fee']/$trader_price));
                            //根据占比更新单个商品时间支付的价格
                            foreach ($value['OrderGoods'] as $k => $v) {
                                //更新实际支付的价格
                                $pay[$k] = $bili2 * $pay_price[$k];
                                //在根据店铺的优惠比例继续计算实际支付的价格
                                M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay[$k]));
                                $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                            }
                            //更新订单的价格及状态
                            M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                        } else {
                            //根据占比更新单个商品时间支付的价格
                            foreach ($value['OrderGoods'] as $k => $v) {
                                //更新实际支付的价格
                                $pay_price[$k] = $bili * $v['goods_price']*$v['goods_num'];
                                M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay_price[$k]));
                                $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                            }
                            //更新订单的价格及状态
                            M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                        }
                    }
                     
                    if ($check !== false) {
                        if($payinfo['status'] != 20){
                            if(strtoupper($apitype) == 'ALIWAPPAY'){
                                $notify = $notify['notify_data'];
                                $data['result'] = serialize($notify);
                                $data['trade_no'] = $notify['trade_no'];
                                $data['buyer_email'] = $notify['buyer_email'];
                                $data['payment'] = $notify['total_fee'];
                                $data['pay_time'] = time();
                                $data['status'] = 20;
                            }else{
                                $data['result'] = serialize($notify);
                                $data['trade_no'] = $notify['trade_no'];
                                $data['buyer_email'] = $notify['buyer_email'];
                                $data['payment'] = $notify['total_fee'];
                                $data['pay_time'] = time();
                                $data['status'] = 20;
                            }
                            M("orderPay")->where(array('pay_sn' => $info['out_trade_no']))->save($data);
                            $where['user_id'] = $payinfo['user_id'];
                            M('users')->where($where)->setInc('user_points', $data['payment']);
                            M('users')->where($where)->setInc('user_orders', 1);
                            M('users')->where($where)->setInc('user_integral',round($data['payment']));
                            //增加商品表的销量
                            addGoodsSale($info['out_trade_no']);
                        }
                    }
                }
                
                if (I('get.method') == "return") {
                    //同步直接跳转成功页面
                    $out_trade_no = I('out_trade_no');
                    $pay_id = auth_encode($out_trade_no);
                    $url = HOME_URL . U('/Pay/result', array('out_trade_no' => $pay_id));
                    redirect($url);
                }else{
                    $pay->notifySuccess();
                }
            }else{
                $this->error("支付失败！");
            }
        }else{
            E("Access Denied");
        }
    }

    
    

    
    
    /* 验证手机是否可用 */
    function yzTel() {
        header("Access-Control-Allow-Origin: *");
        $user_name = I("mobile_phone");
        sleep(1);
        if (empty($user_name)) {
            echo 0;
        }

        $uModel = M("users");
        $data = $uModel->where("user_mobile='%s'", $user_name)->find();
        if (!is_null($data)) {
            echo "kjskfjks";
        } else {
            echo 0;
        }
    }
    
    //获取分类的类别
    public function josn_class(){
        header("Access-Control-Allow-Origin: *");
        $gc_id = I('gc_id');
        $map['parent_id'] = $gc_id;
        $list = M('category')->field('cat_id,cat_name,parent_id,sort_order')->where($map)->select();
        return $this->ajaxReturn($list);
    }
    
    
    //获取地区JSON
    public function AreaJson(){
        
        $id = I('id');
        $transport_id = I('transport_id');
        $map['area_parent_id'] = $id;
        $list = M('area')->field('area_id as id,area_name as name')->where($map)->select();
        $result['data']=$list;
        
        //$transport = M('transport')->where('transport_id ='.$transport_id)->find();
        //$maps['is_default'] = 2;
        $maps['transport_id'] = $transport_id;
        $trans = M('transport_extend')->where($maps)->select();
        foreach ($trans as $key => $value) {
            $arr = explode(',',(trim($value['area_id'],',')));
            $p = array_search($id,$arr);
            if($p !== FALSE){
                //如果传过来的ID存在与特殊区域，后去特殊区域的邮费
                $yunfei = $value['sprice'];
            }
        }
        if($yunfei == 0 ){
            $yunfei = $trans = M('transport_extend')->where('is_default =1 and transport_id ='.$transport_id)->getField('sprice');
        }
//        p($yunfei);
//        if($yunfei == 0){
//            $yunfei = 0;
//        }else{
//            $yunfei = $trans = M('transport_extend')->where('is_default =1 and transport_id ='.$transport_id)->getField('sprice');
//        }
        
        if($yunfei == 0){
            $result['freight'] = "快递费：免运费";
        }else if($yunfei >=99){
            $result['freight'] = "商品不支持发送到此地区！";
        }else{
            $result['freight'] = "快递费：".$yunfei."元";
        }
        
        return $this->ajaxReturn($result);
    }
    

    public function Out() {
        header("Access-Control-Allow-Origin: *");
        session('user_id', null);
        session('user_name', null);
        session('[destroy]');
        $a['status'] = 1;
        $a['msg'] = '退出成功!';
        $this->ajaxReturn($a);
    }
}
